# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
import json

import requests
import scrapy
from scrapy.settings import BaseSettings

from apps.tax_illegal.tax_illegal.items import NetTaxIllegalProItem


class OneByOneSearchTaxIllegalSpider(scrapy.Spider):
    pass


class BaseTaxIllegalSpider(scrapy.Spider):
    Request = scrapy.Request
    FormRequest = scrapy.FormRequest
    province = None
    company_keys = [
        "公",
        "厂",
        "站",
        "校",
        "中",
        "社",
        "部",
        "店",
        "所",
        "处",
        "队",
        "场",
        "行",
        "业",
        "矿",
        "酒吧",
        "馆",
        "坊",
        "户",
        "市",
        "县",
        "区",
        "厅",
    ]

    @classmethod
    def update_settings(cls, settings: BaseSettings) -> None:
        settings.setdict(cls.custom_settings or {}, priority="spider")
        if not cls.province:
            raise NotImplementedError("未设置省份")

    def etax_search(self, **kwargs):
        for i in self.company_keys:
            yield from self.generate_image(None, **{"company_name": i, **kwargs})

    def generate_image(self, response, **kwargs):
        etax_url = kwargs.get("etax_url")
        if etax_url:
            url = f"{etax_url}/xxbg/api/zhsffw/sxsq/yzm/generate"
            data = {"Width": 100, "Height": 32, "CodeCount": 4, "Thickness": 2, "SxzlCode": "GGCX_ZDSSWFAJCX"}
            yield self.FormRequest(
                url,
                body=json.dumps(data),
                headers={"Content-Type": "application/json"},
                callback=self.predict_image,
                method="POST",
                cb_kwargs=kwargs,
                dont_filter=True,
            )

    def predict_image(self, response, **kwargs):
        etax_url = kwargs.get("etax_url")
        if etax_url:
            url = f"{etax_url}/xxbg/api/zhsffw/ggcx/zdsswfajcx/queryZdsswfajs"
            captcha_id = response.json()["Response"]["Data"]["Result"]["id"]
            img_content = response.json()["Response"]["Data"]["Result"]["imageBase64Data"]
            image_res = requests.post(
                "http://129.204.13.211:19952/captcha/v1",
                json={
                    "image": img_content,
                    "secret_key": "ydEc1x9mjg1iqQDLDNELM54zcOOmN1HI",
                    "model_name": "common-captcha-CNNX-GRU-H64-CTC-C1_8800",
                },
            ).json()
            self.logger.info(f"验证码识别结果：{image_res}")
            code = image_res["message"]
            data = {"Id": captcha_id, "Code": code, "Nsrmc": kwargs.get("company_name")}
            yield self.FormRequest(
                url,
                body=json.dumps(data),
                headers={"Content-Type": "application/json"},
                callback=self.parse_etax_search,
                method="POST",
                cb_kwargs=kwargs,
            )

    def parse_etax_search(self, response, **kwargs):
        resp = response.json()
        if resp["Response"]["Data"]["Error"]:
            self.logger.info(f'验证码识别错误，重新识别 {resp["Response"]["Data"]["Error"]}')
            error_times = kwargs.get("error_times", 1)
            if not error_times:
                error_times += 1
                kwargs["error_times"] = error_times
            if error_times > 10:
                self.logger.info("验证码识别错误次数超过10次，放弃验证码识别")
            else:
                yield from self.generate_image(None, **kwargs)
        else:
            data_list = resp["Response"]["Data"]["Result"]
            for data in data_list:
                item = NetTaxIllegalProItem()
                item.province = self.province
                item.company_name = data["nsrmc"]
                item.address = data["zcdz"]
                item.taxpayer_id = data["nsrsbh"]
                item.legal_representative = (
                    "，".join([data.get(i) or "" for i in ["fddbrxm", "fddbrfzrxbmc", "fddbrsfzjlxmc", "fddbrsfzjhm"]])
                    if data.get("fddbrxm")
                    else ""
                )
                item.illegal_legal_representative = (
                    "，".join(
                        [
                            data.get(i) or ""
                            for i in [
                                "wfssfssfddbrzrxm",
                                "wfssfssfddbrzrxbmc",
                                "wfssfssfddbrzrzjmc",
                                "wfssfssfddbrzrzjhm",
                            ]
                        ]
                    )
                    if data.get("wfssfssfddbrzrxm")
                    else ""
                )
                item.resp_financial_head = (
                    "，".join(
                        [
                            data.get(i) or ""
                            for i in [
                                "jfypjqdfyzjzzdcwryxm",
                                "jfypjqdfyzjzzdcwryxb",
                                "jfypjqdfyzjzzdcwryzjmc",
                                "jfypjqdfyzjzzdcwrysfzhm",
                            ]
                        ]
                    )
                    if data.get("jfypjqdfyzjzzdcwryxm")
                    else ""
                )
                item.resp_intermediary = data["fyzjzrdsszyfwjgmc"]
                item.illegal_status = data["wfxz"]
                item.illegal_facts = data["zywfss"]
                item.basis_and_punishment = data["flyjjclcfqk"]
                yield item
